//
//  WJYRadioPlayerViewController.m
//  WWLNetease
//
//  Created by dllo on 15/12/29.
//  Copyright © 2015年 Echo.Jobs. All rights reserved.
//

#import "WJYRadioPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

@interface WJYRadioPlayerViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)NSMutableDictionary *dic;/**<装有当前页面正在播放的音频信息的字典*/

@property (nonatomic, retain)UIImageView *imageV;/**<毛玻璃背景*/

@property (nonatomic, retain)UIImageView *displayImageV;/**<用于展示的图片*/

@property (nonatomic, retain)NSMutableArray *array;/**<装列表的数组*/

@property (nonatomic, assign)NSInteger page; /**<页数*/

@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)AVPlayerViewController *player; /**<播放器*/

@property (nonatomic, assign)NSInteger playCont;/**<当前播放的是第几个*/

@property (nonatomic, assign)BOOL isPlay;

@property (nonatomic, retain)UIImageView *myView;

@property (nonatomic ,retain)UIButton *playButton;

@end

@implementation WJYRadioPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化页数
    self.page = 0;
    
    // 初始化播放
    self.isPlay = YES;
    
    // 初始化播放数目
    self.playCont = 0;
    
    // 创建视图
    [self createView];
    
}
#pragma mark- 创建视图
- (void)createView
{
    self.imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.4)];
    [self.view addSubview:self.imageV];

    
    // 毛玻璃
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEffectView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.4);
    visualEffectView.alpha = 1.0;
    [self.view addSubview:visualEffectView];

    
    // 展示图片
    self.displayImageV = [[UIImageView alloc]initWithFrame:CGRectMake(self.imageV.frame.size.width / 3, 45, self.imageV.frame.size.width / 3, self.imageV.frame.size.width / 3)];
    self.displayImageV.layer.masksToBounds = YES;
    self.displayImageV.layer.cornerRadius = self.imageV.frame.size.width / 3 / 2;
    self.displayImageV.backgroundColor = [UIColor whiteColor];
    [visualEffectView addSubview:self.displayImageV];
   
    
    // 上一个按钮
    UIButton *lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    lastButton.frame = CGRectMake(self.imageV.frame.size.width / 4 - 40, self.imageV.frame.size.height / 3, 45, 45);
    [lastButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shangyiqu.png"] forState:UIControlStateNormal];
    [lastButton addTarget:self action:@selector(lastButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [visualEffectView addSubview:lastButton];
    

    
    // 播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(self.imageV.frame.size.width / 2 - self.imageV.frame.size.width / 3 / 2 / 2 / 2, 45 * 2, self.imageV.frame.size.width / 9, self.imageV.frame.size.width / 9);
    [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang.png"] forState:UIControlStateNormal];
//    [self.playButton setImage:[UIImage imageNamed:@"iconfont-iconfontzanting.png"] forState:UIControlStateSelected];
    [self.playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [visualEffectView addSubview:self.playButton];
    
    // 下一个按钮
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(self.imageV.frame.size.width / 4 * 3 - 5 , self.imageV.frame.size.height / 3, 45, 45);
    [nextButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xiayiqu.png"] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [visualEffectView addSubview:nextButton];
    
    // 播放器
    self.player = [[AVPlayerViewController alloc]init];
    self.player.view.frame = CGRectMake(0, self.view.frame.size.height * 0.4 , self.view.frame.size.width + 40, 43);
    self.player.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.player.view];
    
    
    
    [self createTableView];
}

#pragma mark- 创建TableView
- (void)createTableView
{
    // 留白
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 初始化页数
    self.page = 0;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 0.3, self.view.frame.size.width, self.view.frame.size.height  * 0.6 - 45)];
    
    // 代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // tableView Footer
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    // 注册
    [self.tableView registerClass:[WJYRadioPlayerTableViewCell class] forCellReuseIdentifier:@"RadioDetailPlayTableViewCell"];
    
    // 添加并释放
    [self.view addSubview:self.tableView];
    
    
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewHeaderRefresh)];
    [self.tableView.mj_header beginRefreshing];
    
    // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewFooterRefresh)];
    
   
    // 拼接网址
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/0-10.html", self.tid];

    


    [self getData:url];
  
    
}

#pragma mark- 上一个按钮
- (void)lastButtonAction{
    
    // 暂停
    [self.player.player pause];
    
//    [self.playButton setImage:[UIImage imageNamed:@"iconfont-iconfontzanting.png"] forState:UIControlStateSelected];
    
    // 判断
    if (self.playCont == 0) {
        


        
    }else {
        
        // 改变当前播放数目
        self.playCont = self.playCont - 1;
        
        // 重新在数组中获取数据
        WJYRadioPlayerModel *radioPlay = [[WJYRadioPlayerModel alloc]init];
        radioPlay = [self.array objectAtIndex:self.playCont];
        
        // 重新拼接网址
        NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", radioPlay.docid];
        
        // 重新进行数据请求
        [self getDataForPlay:str tid:radioPlay.docid];
        
    }
    
}

#pragma mark- 下一个按钮
- (void)nextButtonAction{
    
    // 暂定
    [self.player.player pause];
    
//    [self.playButton setImage:[UIImage imageNamed:@"iconfont-iconfontzanting.png"] forState:UIControlStateSelected];
    
    // 判断
    if (self.playCont  > self.array.count - 2) {
        
        NSLog(@"--------------------");
        
    }else {
        
        self.playCont = self.playCont + 1;
        WJYRadioPlayerModel *radioPlay = [[WJYRadioPlayerModel alloc]init];
        radioPlay = [self.array objectAtIndex:self.playCont];
        NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", radioPlay.docid];
        
        [self getDataForPlay:str tid:radioPlay.docid];
        
    }
    
}

#pragma mark- 下拉刷新
- (void)tableViewHeaderRefresh
{
    
    // 拼接网址
    NSString *url2 = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/0-10.html", self.tid];
    
    [UIView animateWithDuration:10 animations:^{
        
        // 解析数据
        [self getDataForFresh:url2];
  
    }];
    
    
    // 页数置0
    self.page = 0;
}

#pragma mark- 上拉加载
- (void)tableViewFooterRefresh
{
    // 页数增加
    self.page = self.page + 10;
    
    // 拼接网址
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/%ld-10.html", self.tid, self.page];
    
    // 数据解析
    [self getDataForLoad:url];
    
    
}

#pragma mark- 获取刷新数据
- (void)getDataForFresh:(NSString*)url
{
    
    // AFN解析
    
    [AppTools getDataWithURL:url Block:^(id result) {
        
        // 可变数组初始化
        self.array = [NSMutableArray array];
        
        // 取出数据
        NSArray *arr = [result objectForKey:self.tid];
        
        // 遍历数组
        for (NSDictionary *tempDic in arr) {
            
            // 初始化
            WJYRadioPlayerModel *radioPlay = [[WJYRadioPlayerModel alloc]init];
            
            // 传值
            radioPlay.imageUrl = [tempDic objectForKey:@"imgsrc"];
            radioPlay.source = [tempDic objectForKey:@"source"];
            radioPlay.title = [tempDic objectForKey:@"title"];
            radioPlay.ptime = [tempDic objectForKey:@"ptime"];
            radioPlay.docid = [tempDic objectForKey:@"docid"];
            radioPlay.size = [tempDic objectForKey:@"size"];
            // 添加进数组
            [self.array addObject:radioPlay];
            
            
        }
        
        // 重载数据
        [self.tableView reloadData];
        
        // 结束刷新
        [self.tableView.mj_header endRefreshing];

        
    } ErrorBlock:^(NSError *error) {
        
        
    }];
    
    
}

#pragma mark- 获取加载数据
- (void)getDataForLoad:(NSString*)url
{
    
    // AFN解析
    
    [AppTools getDataWithURL:url Block:^(id result) {
        
        // 将数据存入数组
        NSArray *arr = [result objectForKey:self.tid];
        
        // 遍历数组
        for (NSDictionary *tempDic in arr) {
            
            // 初始化
            WJYRadioPlayerModel *radioPlay = [[WJYRadioPlayerModel alloc]init];
            
            // 传值
            radioPlay.imageUrl = [tempDic objectForKey:@"imgsrc"];
            radioPlay.source = [tempDic objectForKey:@"source"];
            radioPlay.title = [tempDic objectForKey:@"title"];
            radioPlay.ptime = [tempDic objectForKey:@"ptime"];
            radioPlay.docid = [tempDic objectForKey:@"docid"];
            radioPlay.size = [tempDic objectForKey:@"size"];
            
            // 添加进数组
            [self.array addObject:radioPlay];
            
        }
        
        // 重载数据
        [self.tableView reloadData];
        
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        
    } ErrorBlock:^(NSError *error) {
        
        
    }];
    

    
}

#pragma mark-  进入页面时调用的网络请求
- (void)getData:(NSString *)url
{
    // AFN解析
    [AppTools getDataWithURL:url Block:^(id result) {
        // 可变数组初始化
        self.array = [NSMutableArray array];
        
        // 去数据存入数组
        NSArray *arr = [result objectForKey:self.tid];
        
        // 遍历数据
        for (NSDictionary *dic in arr) {
            
            // 初始化
            WJYRadioPlayerModel *radioPlay = [[WJYRadioPlayerModel alloc]init];
            
            // 传值
            radioPlay.imageUrl = [dic objectForKey:@"imgsrc"];
            radioPlay.source = [dic objectForKey:@"source"];
            radioPlay.title = [dic objectForKey:@"title"];
            radioPlay.ptime = [dic objectForKey:@"ptime"];
            radioPlay.docid = [dic objectForKey:@"docid"];
            radioPlay.size = [dic objectForKey:@"size"];
            
            // 添加进数组
            [self.array addObject:radioPlay];
        }
        
        // 取出第一个元素
        WJYRadioPlayerModel *radioPlayM = [self.array firstObject];
        
        // 拼接网址
        NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", radioPlayM.docid];
        
        // 获取数据
        [self getDataForPlay:str tid:radioPlayM.docid];
        
        // 重载界面
        [self.tableView reloadData];
        
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        
    } ErrorBlock:^(NSError *error) {
        
        
        
    }];
    
    
}

#pragma mark- 执行网络申请,并播放音频
- (void)getDataForPlay:(NSString*)url tid:(NSString *)tid
{
    
    // AFN解析
    [AppTools getDataWithURL:url Block:^(id result) {
        
        // 取数据存入字典
        NSDictionary *dic = [result objectForKey:tid];
        
        // 取出网址
        NSString *source_url = [dic objectForKey:@"source_url"];
        
        // 播放器网址
        self.player.player = [AVPlayer playerWithURL:[NSURL URLWithString:source_url]];
        
        //背景图
        NSArray *arr = [dic objectForKey:@"img"];
        NSDictionary *dic1 = [arr firstObject];
        NSString *str = [dic1 objectForKey:@"src"];
        
        [self.imageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"audionews_play_bg@2x.png"]];
        [self.displayImageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"audionews_play_bg@2x.png"]];
        
        
        
        [self.displayImageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"audionews_play_bg@2x.png"]];
        
        // 播放器播放
        [self.player.player play];
        
    } ErrorBlock:^(NSError *error) {
        
        
    }];

    
}

#pragma mark- TableView方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60 * SIZE;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WJYRadioPlayerTableViewCell *RadioDetailPlayTableViewCell = [tableView dequeueReusableCellWithIdentifier:@"RadioDetailPlayTableViewCell"];
    
    WJYRadioPlayerModel *radioPlay = [self.array objectAtIndex:indexPath.row];
    
    RadioDetailPlayTableViewCell.playerModel = radioPlay;
    
    return RadioDetailPlayTableViewCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 暂定播放
    [self.player.player pause];
    
    WJYRadioPlayerModel *radioPlay = [self.array objectAtIndex:indexPath.row];
    
    // 当前播放
    self.playCont = indexPath.row;
    
    // 拼接网址
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", radioPlay.docid];
    
    // 解析并播放
    [self getDataForPlay:str tid:radioPlay.docid];
    
}

#pragma mark- 离开页面时停止播放
- (void)viewWillDisappear:(BOOL)animated
{
    [self.player.player seekToTime:kCMTimeZero];
    [self.player.player pause];
}

- (void)playAction:(UIButton *)btn{
    
    if (self.isPlay == YES) {
        [self stopAction];
    }else{
        [self beginAction];
    }
    
    btn.selected = !btn.selected;
}

- (void)beginAction{
    

    self.isPlay = YES;
    
    // 显示
//    self.imageV.hidden = YES;
    
    // 播放
    [self.player.player play];
}

- (void)stopAction{
    
    self.isPlay = NO;
    
    // 隐藏
//    self.imageV.hidden = NO;
    
    // 停止播放
    [self.player.player seekToTime:kCMTimeZero];
    [self.player.player pause];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based ap plication, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end




